﻿var defaultIndex = 0;

$(document).ready(function () {
    var dropDownList = $("#dropDownList");
    var contentTable = $("#contentTable");
    var enablePostBack = $("#" + enablePostBackControlID).val();
    var title = $("#dropDown_Title");

    $("dd", contentTable).html("");
    title.click(function () {
        contentTable.show();
    })
    dropDownList.mouseleave(function () {
        contentTable.hide();
    })

    var dataSource = $("#" + dataSourceControlID).val();
    if (dataSource == '') return;
    var dataSource = $.parseJSON(dataSource);

    var selectedValue = $("#" + selectedValueControlID).val();
    var selectedIndex = defaultIndex;

    $.each(dataSource, function (index, data) {
        var aElement = $("<a href='#'>" + data.value + "</a>");
        aElement.click(function () {
            select(dataSource, index);
            contentTable.hide();
            if (enablePostBack.toLowerCase() == 'true' && index != selectedIndex) {
                eval(eventReference);
            }
        });
        $("dd", contentTable).append(aElement);
        if (selectedValue == data.key) {
            selectedIndex = index;
        }
    })

    if (selectedValue == '') {
        select(dataSource, defaultIndex);
    }
    else {
        select(dataSource, selectedIndex);
    }

    var contentWidth = $("#contentTable").width();
    if (contentWidth != 0) {
        $("#dropDownList").width($("#contentTable").width());
    }
});

function selectDropDownItem(index) {
    var dataSource = $("#" + dataSourceControlID).val();
    if (dataSource == '') return;
    var dataSource = $.parseJSON(dataSource);

    select(dataSource, index);
}

function select(data, selectedIndex) {
    var contentTable = $("#contentTable");
    var dropDownList = $("#dropDownList");
    var elements = $("dd a", contentTable);

    elements.removeClass("DropDownBoxDownSelected");

    $.each(elements, function (index, element) {
        if (selectedIndex == index) {
            $(element).addClass("DropDownBoxDownSelected");
            $("dt", dropDownList).html($(element).html());
            return false;
        }
    })

    $("#" + selectedTextControlID).val(data[selectedIndex].value);
    $("#" + selectedValueControlID).val(data[selectedIndex].key);
    $("#" + selectedIndexControlID).val(selectedIndex);
}

